package com.test.template.publish.config.fac;

import com.elecbook.content.model.po.Contribute;
import com.test.template.publish.config.ApiConfig;
import com.test.template.publish.config.ControllerConfig;
import com.test.template.publish.config.manager.VelocityConfigManager;
import com.test.template.tool.Tool;

import java.util.concurrent.ConcurrentHashMap;

public class ControllerConfigFactory implements VelocityTemplateConfigFactory<ControllerConfig> {

    ConcurrentHashMap<String, ControllerConfig> configHashMap = new ConcurrentHashMap<>();

    // **单例定义
    // 私有静态变量保存唯一实例
    private static volatile ControllerConfigFactory instance = null;

    // **单例定义
    // 公共静态方法提供全局访问点
    public static ControllerConfigFactory getInstance() {
        if (instance == null) {
            synchronized (XmlSubmitConfigFactory.class) {
                if (instance == null) {
                    instance = new ControllerConfigFactory();
                    init();
                }
            }
        }
        return instance;
    }

    private static void init() {
        ControllerConfig contributeConfig = buildBasicConfig("contribute",
                "com.elecbook.content.api",
                Contribute.class);
        getInstance().addConfig("contribute", contributeConfig);
    }

    /**
     * 我们规定clazzPo前一级别的包为
     * domainPackage,即为domainName
     *
     * @param tableName
     * @param packageName
     * @param clazzPo
     * @return
     */
    private static ControllerConfig buildBasicConfig(String tableName, String packageName, Class<?> clazzPo) {
        ControllerConfig config = new ControllerConfig();
        config.setTableName(tableName);
        // 获取entityName
        String poPackage = clazzPo.getPackage().getName();
        String entityName = Tool.subStringBeforePunctuationCount(poPackage, ".", 1);
        config.setDomainName(entityName);
        // controller的包名称
        config.setPackageName(packageName);
        // 初始化
        config.innerGenerate();
        return config;
    }


    // 私有构造函数防止实例化
    private ControllerConfigFactory() {

    }


    @Override
    public ControllerConfig getConfig(String key) {
        return configHashMap.get(key);
    }

    @Override
    public void addConfig(String key, ControllerConfig config) {
        configHashMap.put(key, config);
    }


    @Override
    public void addConfig(VelocityConfigManager manager) {
        ControllerConfig config = buildBasicConfig(manager.getTableName(), manager.getControllerPackage(),manager.getClazzPo());
        getInstance().addConfig(manager.getTableName(), config);
    }

}
